

def parse_head(head: str) -> (dict, list):
    """
    解析 HTTP 头部数据
    :param head:
    :return:
    """
    text_lines = head.split('\n')
    lines = [x.strip() for x in text_lines if x.strip()]

    hmap = {}

    for line in lines:
        segs = line.split(':', 1)

        if segs.__len__() == 1:  # 没有冒号的行
            if line.startswith('HTTP/'):
                segs = lines[0].split()
                hmap['_type'] = 'response'
                hmap['_protocol'] = segs[0]
                hmap['_code'] = segs[1]
                hmap['_msg'] = segs[2]

            elif line.startswith('GET ') or line.startswith('POST ') or line.startswith('DELETE ') \
                    or line.startswith('UPDATE ') or line.startswith('PATCH '):
                segs = lines[0].split()
                hmap['_type'] = 'request'
                hmap['_method'] = segs[0].strip()
                hmap['_uri'] = segs[1].strip()
                hmap['_protocol'] = segs[2].strip()

        else:  # 有冒号的普通行，分解成 key-value
            hmap[segs[0].strip()] = segs[1].strip()

    return hmap, lines


if __name__ == '__main__':
    request_head = '''
POST /licensemanager/LicenseManagerService.svc HTTP/1.1

SOAPAction: ValidateLicenseLease

Content-Type: text/xml; charset="utf-8"

Content-Length: 888

Accept-Encoding: deflate, gzip

User-Agent: Altium Designer

Host: 192.168.1.113:9780

Connection: Keep-Alive

Cache-Control: no-cache
'''

    parse_head(request_head)
